package model.server;

import com.alibaba.fastjson.JSONObject;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * 多线程监听客户机发送过来的数据，并转发到对应客户机
 * 传输数据使用Json数据，数据有type、from、to、msg四个键。
 * type值决定是心跳包（6）、连接请求消息（1）、私聊消息（2）、群聊消息（3）暂时只用到这4个值
 * from是发送方
 * to可能是一个客户（私聊）,也可能是多个客户组成的List（群聊），取决于type
 * msg是发送的消息
 */
public class ServerThread extends Thread{
    private Socket socket;
    private ObjectOutputStream out = null;
    private ObjectInputStream in =null;

    public ServerThread(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        JSONObject object = null;
        try {
            in = new ObjectInputStream(socket.getInputStream());
            out = new ObjectOutputStream(socket.getOutputStream());

            while (true) {
                object = (JSONObject) in.readObject();
                System.out.println(object);
                String type = object.getString("type");

                if (type.equals("1")) {
                    String from = object.getString("from");
                    System.out.println("..." + from +"上线...");
                    ChatManager.getInstance().add(from, out);
                } else if (type.equals("2")) {
                    String to = object.getString("to");
                    for (Map.Entry<String, ObjectOutputStream> entry : ChatManager.getInstance().getMap().entrySet()) {
                        if (entry.getKey().equals(to)) {
                            try {
                                entry.getValue().writeObject(object);
                            } catch (Exception e) {
                                System.out.println(to + "暂时不在线...");
                            }
                        }
                    }
                } else if (type.equals("3")) {
                    List<String> toList = (List<String>) object.get("to");
                    System.out.println(toList);
                    for (String to : toList) {
                        for (Map.Entry<String, ObjectOutputStream> entry : ChatManager.getInstance().getMap().entrySet()) {
                            if (entry.getKey().equals(to) && !to.equals(object.get("from"))) {
                                try {
                                    entry.getValue().writeObject(object);
                                } catch (Exception e) {
                                    System.out.println(to + "暂时不在线...");
                                }

                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

}
